<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="所属项目" prop="dictType">
        <el-select v-model="projectCurrentName" @change="getInfo()">
          <el-option v-for="project in projectList" :key="project.id" :label="project.name"
            :value="parseInt(project.id)"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input v-model="queryParams.name" clearable placeholder="请输入名称" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="开始时间" prop="startTime">
        <el-date-picker v-model="queryParams.startTime" clearable placeholder="选择开始时间" type="date"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="截止时间" prop="endTime">
        <el-date-picker v-model="queryParams.endTime" clearable placeholder="选择截止时间" type="date"
          value-format="yyyy-MM-dd">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select v-model="queryParams.status" clearable placeholder="请选择任务状态">
          <el-option v-for="dict in dict.type.moe_task_status" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-has-permi="['system:task:add']" icon="el-icon-plus" plain size="mini" type="primary"
          @click="handleAdd">新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button icon="el-icon-sort" plain size="mini" type="info" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="taskList" :default-expand-all="isExpandAll"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" row-key="id">
      <el-table-column align="center" label="名称" prop="name" />
      <el-table-column align="center" label="开始时间" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="截止时间" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="任务状态" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.moe_task_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="工作进度" width="130">
        <template slot-scope="scope">
          <el-progress v-if="scope.row.taskParentId == 0" :percentage="scope.row.workload"></el-progress>
        </template>
      </el-table-column>
      <el-table-column align="center" label="任务评估" prop="remark">
        <template slot-scope="scope">
          <el-button v-has-permi="['system:task:evaluation']" icon="el-icon-edit" size="mini" type="text"
            @click="handerEvaluation(scope.row, 1)">评估
          </el-button>
          <el-button v-has-permi="['system:task:queryEvaluation']" icon="el-icon-edit" size="mini" type="text"
            @click="handerEvaluation(scope.row, 2)">查看评估
          </el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button v-has-permi="['system:task:edit']" icon="el-icon-edit" size="mini" type="text"
            @click="handleUpdate(scope.row)">修改
          </el-button>
          <el-button v-has-permi="['system:task:query']" icon="el-icon-plus" size="mini" type="text"
            @click="getTastInfo(scope.row)">详情
          </el-button>
          <el-button v-has-permi="['system:task:add']" icon="el-icon-plus" size="mini" type="text"
            @click="handleAdd(scope.row)">新增
          </el-button>
          <el-button v-has-permi="['system:task:remove']" icon="el-icon-delete" size="mini" type="text"
            @click="handleDelete(scope.row)">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 评估弹窗 -->
    <el-dialog title="评估" :visible.sync="evaluationOpen" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="评估" prop="remark">
          <el-input v-model="form.remark" :min-height="192" v-if="evaluationIsShow" />
          <div v-else>{{ form.remark }}</div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="evaluationCancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="500px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" :disabled="taskFormTag" placeholder="请输入名称" />
        </el-form-item>
        <span></span>
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="form.startTime" :disabled="taskFormTag" :picker-options="pickerStart" clearable
            placeholder="请选择开始时间" type="date" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item label="截止时间" prop="endTime">
          <el-date-picker v-model="form.endTime" :disabled="taskFormTag" :picker-options="pickerEnd" clearable
            placeholder="请选择截止时间" type="date" value-format="yyyy-MM-dd" />
        </el-form-item>
        <el-form-item v-if="form.taskParentId == 0" align="center" label="任务占比" prop="proportion">
          <el-slider v-model="form.proportion" :disabled="taskFormTag" :max=projectUse show-input>
          </el-slider>
        </el-form-item>
        <el-form-item v-if="form.taskParentId == 0" :disabled="taskFormTag" align="center" label="工作进度" prop="workload">
          <el-slider v-model="form.workload" show-input>
          </el-slider>
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" :disabled="taskFormTag" type="textarea" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addTask, delTask, getTask, listTask, updateTask } from "@/api/system/task";
import { getAllowableProportion, getProject, listProject } from "@/api/system/project";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Task",
  dicts: ['moe_task_status'],
  components: {
    Treeselect
  },
  data () {
    return {
      value1: [],
      isProjectAdmin: false,
      evaluation: false,
      // 遮罩层
      loading: true,
      // 项目已使用
      projectUse: null,
      // 是否为增加
      isAdd: true,
      // 显示搜索条件
      showSearch: true,
      // 评估查看或修改
      evaluationIsShow: false,
      // 表单输入
      taskFormTag: false,
      // 任务表格数据
      taskList: [],
      // 任务树选项
      taskOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示评估弹窗
      evaluationOpen: false,
      // 是否展开，默认全部展开
      isExpandAll: true,
      // 重新渲染表格状态
      refreshTable: true,
      // 当前项目的开始时间
      projectStartTime: null,
      // 当前选中在项目
      projectCurrentName: null,
      // 当前项目的结束时间
      projectEndTime: null,
      // 当前任务的父任务的开始时间
      parentTaskStartTime: null,
      // 当前任务的父任务的结束时间
      parentTaskEndTime: null,
      // 查询参数
      queryParams: {
        projectId: null,
        name: null,
        startTime: null,
        endTime: null,
        status: null,
      },
      // 项目管理表格数据
      projectList: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        taskParentId: [
          { required: true, message: "父级ID不能为空", trigger: "blur" }
        ],
        proportion: [
          { required: true, message: "任务占比不能为空", trigger: "blur" }
        ],
        workload: [
          { required: true, message: "工作量不能为空", trigger: "blur" }
        ],
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" }
        ],
        startTime: [
          { required: true, message: "开始时间不能为空", trigger: "blur" }
        ],
        endTime: [
          { required: true, message: "截止时间不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "任务状态不能为空", trigger: "change" }
        ],
      },
      pickerStart: {
        disabledDate: (time) => {
          if (this.parentTaskStartTime && this.parentTaskEndTime) {
            if (this.form.endTime) {
              return time.getTime() < new Date(this.parentTaskStartTime).getTime() - 86400000 || time.getTime() > new Date(this.form.endTime).getTime()
            } else {
              return time.getTime() < new Date(this.parentTaskStartTime).getTime() - 86400000 || time.getTime() > new Date(this.parentTaskEndTime).getTime()
            }
          } else {
            if (this.form.endTime) {
              return time.getTime() < new Date(this.projectStartTime).getTime() - 86400000 || time.getTime() > new Date(this.form.endTime).getTime()
            } else {
              return time.getTime() < new Date(this.projectStartTime).getTime() - 86400000 || time.getTime() > new Date(this.projectEndTime).getTime()
            }
          }
        }
      },
      pickerEnd: {
        disabledDate: (time) => {
          if (this.parentTaskStartTime && this.parentTaskEndTime) {
            if (this.form.startTime) {
              return time.getTime() < new Date(this.form.startTime).getTime() - 86400000 || time.getTime() > new Date(this.parentTaskEndTime).getTime()
            } else {
              return time.getTime() < new Date(this.parentTaskStartTime).getTime() - 86400000 || time.getTime() > new Date(this.parentTaskEndTime).getTime()
            }
          } else {
            if (this.form.startTime) {
              return time.getTime() < new Date(this.form.startTime).getTime() - 86400000 || time.getTime() > new Date(this.projectEndTime).getTime()
            } else {
              return time.getTime() < new Date(this.projectStartTime).getTime() - 86400000 || time.getTime() > new Date(this.projectEndTime).getTime()
            }
          }
        }
      },
    };
  },
  created () {
    this.getList();
    this.getProjectList();
    this.ProjectPower()
  },
  watch: {
    '$route.query.id': {
      handler () {
        this.getList();
        this.getProjectList();
      }
    },
  },
  methods: {
    // 任务详情
    async getTastInfo (row) {
      this.taskFormTag = true
      this.reset();
      let res = await getTask(row.id)
      this.form = res.data
      this.open = true
    },

    // 评估新增
    handerEvaluation (row, number) {
      if (number == 1) {
        this.evaluationIsShow = true
      } else {
        this.evaluationIsShow = false
      }
      this.form = row
      this.evaluationOpen = true
    },
    ProjectPower () {
      // 获取当前登录的角色id
      let roleRole = localStorage.getItem('currentRole')
      if (roleRole === 'project-admin') {
        this.evaluation = true
        this.isProjectAdmin = true
      }
      if (roleRole === 'project-manager') {
        this.evaluation = false
        this.isProjectAdmin = true
      }
      if (roleRole === 'admin') {
        this.evaluation = true
        this.isProjectAdmin = true
      }
    },

    getInfo () {
      listTask({ projectId: this.projectCurrentName }).then(response => {
        this.taskList = this.handleTree(response.data, "id", "taskParentId");
        this.loading = false;
      });
    },

    /** 查询任务列表 */
    getList () {
      this.loading = true;
      this.queryParams.projectId = this.$route.query.id
      listTask(this.queryParams).then(response => {
        this.taskList = this.handleTree(response.data, "id", "taskParentId");
        this.loading = false;
      });
    },
    /** 转换任务数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    /** 查询任务下拉树结构 */
    getTreeselect () {
      listTask().then(response => {
        this.taskOptions = [];
        const data = { id: 0, name: '顶级节点', children: [] };
        data.children = this.handleTree(response.data, "id", "taskParentId");
        this.taskOptions.push(data);

      });
    },
    /** 初始化获取项目管理列表 */
    getProjectList () {
      this.loading = true;
      listProject().then(response => {
        this.projectList = response.rows
        this.loading = false;
      });
    },

    // 根据项目id查询该项目的详细信息
    async getProjectInfo () {
      this.reset()
      let response = await getProject(this.form.projectId)
      this.projectStartTime = response.data.startTime
      this.projectEndTime = response.data.endTime
      this.projectStatus = response.data.status
    },
    // 评估弹窗取消
    evaluationCancel () {
      this.evaluationOpen = false
      this.form.mask = ''
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        id: null,
        projectId: this.$route.query.id,
        taskParentId: null,
        proportion: 0,
        workload: 0,
        name: null,
        description: null,
        startTime: null,
        endTime: null,
        finishTime: null,
        status: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    async handleAdd (row) {
      this.taskFormTag = false
      await this.getProjectInfo();
      if (this.projectStatus === "0") {// 已审批、已通过
        this.$modal.msgWarning("该项目已验收，无法继续修改");
      } else if (this.projectStatus === "2") {// 已审批、未通过
        this.$modal.msgWarning("该项目等待验收，暂不支持修改");
      } else if (this.projectStatus === "3") {// 已结束
        this.$modal.msgWarning("该项目已结束，无法继续修改");
      } else {
        let res = await getAllowableProportion(this.form.projectId)
        this.projectUse = 100 - res.data
        if (this.projectUse == 0) {
          this.open = false
          this.$message.error('任务分配额已满');
          return
        } else {
          this.open = true
        }
        this.reset();
        this.getTreeselect();
        // 判断
        if (row != null && row.id) {
          this.form.taskParentId = row.id;
          this.parentTaskStartTime = row.startTime
          this.parentTaskEndTime = row.endTime
        } else {
          this.form.taskParentId = 0;
          this.parentTaskStartTime = null
          this.parentTaskEndTime = null
        }
        this.title = "添加任务";
      }
    },
    /** 展开/折叠操作 */
    toggleExpandAll () {
      this.refreshTable = false;
      this.isExpandAll = !this.isExpandAll;
      this.$nextTick(() => {
        this.refreshTable = true;
      });
    },
    /** 修改按钮操作 */
    async handleUpdate (row) {
      this.taskFormTag = false
      await this.getProjectInfo();
      if (this.projectStatus === "0") {// 已审批、已通过
        this.$modal.msgWarning("该项目已验收，无法继续修改");
      } else if (this.projectStatus === "2") {// 已审批、未通过
        this.$modal.msgWarning("该项目等待验收，暂不支持修改");
      } else if (this.projectStatus === "3") {// 已结束
        this.$modal.msgWarning("该项目已结束，无法继续修改");
      } else {
        let projectResponse = await getAllowableProportion(this.form.projectId)
        this.projectUse = 100 - projectResponse.data
        if (row != null && row.taskParentId != 0) {
          getTask(row.taskParentId).then(response => {
            this.parentTaskStartTime = response.data.startTime
            this.parentTaskEndTime = response.data.endTime
          }
          );
        } else {
          this.parentTaskStartTime = null
          this.parentTaskEndTime = null
        }
        getTask(row.id).then(response => {
          this.form = response.data;
          this.form.startTime = response.data.startTime + ' 00:00:00'
          this.form.endTime = response.data.endTime
          this.projectUse = 100 - projectResponse.data + response.data.proportion;
          this.title = "修改任务";
          this.open = true
        });
      }
    },
    /** 提交按钮 */
    submitForm () {
      if (this.projectCurrentName) {
        this.form.projectId = this.projectCurrentName
      } else {
        this.form.projectId = this.$route.query.id
      }

      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.evaluationOpen = false
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.evaluationOpen = false
              this.getList();

            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.$modal.confirm('是否确认删除任务编号为"' + row.id + '"的数据项？').then(function () {
        return delTask(row.id);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
        // 重新调用
        getAllowableProportion(this.$route.query.id).then(Response => {
          this.projectUse = Response.data
          this.projectUse = 100 - this.projectUse
        })
      });
    },
  },
};
</script>

<style>
.app-container {
  user-select: none !important;
}
</style>
